<template>
  <div class="project-tree-page">
    <header>
      <!-- 项目树划分变更 -->
      <Row type="flex" justify="start" align="middle">
        <Col span="3"><h2>项目树划分</h2></Col>
        <Col span="21"
          ><Button
            class="btn-color"
            style="color:#fff"
            @click="changeToRecordList"
            type="primary"
            >查看变更记录</Button
          >
          <Button class="btn-color" @click="multipleInput">批量导入</Button>
          <Button v-permission='"project:tree:admin"' class="btn-color" :disabled="btnDisabled.checkedHTD" @click="adminInput">管理员导入</Button>

          </Col
        >
      </Row>
    </header>
    <header style="margin-top:30px">
      <Row type="flex" justify="start" align="middle">
        <Col span="6" >
         <h3>{{projectName}}</h3></Col>
        <Col span="18" class="padding-left">
          <Button
            class="btn-color"
            v-show="showSwitch.btnGroup"
            @click="addTreeNodeEvent(0)"
            :disabled="btnDisabled.addBrother"
            >新增同级</Button
          >
          <Button
            class="btn-color"
            v-show="showSwitch.btnGroup"
            @click="addTreeNodeEvent(1)"
            :disabled="btnDisabled.addSon"
            >新增下级</Button
          >
          <Button
            class="btn-color"
            :disabled="btnDisabled.copy"
            @click="copyTreeNode"
            >复制层级</Button
          >
          <Button
            class="btn-color"
            :disabled="btnDisabled.copy"
            @click="replaceTreeNode"
            >批量替换</Button
          >
          <Button
            class="btn-color"
            :disabled="btnDisabled.batch"
            @click="batchAddNode"
            >批量添加部位</Button
          >
          <Button
            v-permission='"project:tree:excel"'
            class="btn-color"
            @click="exportExcel"
          >导出excel</Button>

          <Button
            v-permission='"project:tree:agree"'
            @click="submitPrimaryApproval"
            type="primary"
            :disabled="btnDisabled.primary"
            v-show="!showSwitch.projectPart"
            >提交审批</Button
          >
          <Button
            v-permission='"project:tree:edit"'
            @click="toOldTreelog"
            v-show="showSwitch.projectPart"
            class="btn-color"
            >项目树变更</Button
          >
        </Col>
        <!-- <Col span="9"></Col> -->
      </Row>
    </header>
    <section class="section">
      <Row type="flex" justify="start" align="top">
        <Col span="6" class="padding-right my-scollor">
          <Htdlist
            @getContractTree="getContractTree"
            ref="htdList"
            :tree="treeData"

          />
        </Col>
        <Col span="18" class="padding-left my-scollor">
          <template>
            <!-- 新项目树区域/edit编辑项目树 -->
            <section v-show="showSwitch.treeEditState" class="aside-tree">
              <Tree
                :data="treeData.newTree"
                select-node
                :render="renderContent"
                @on-toggle-expand="sendSwitchNode"
              ></Tree>
            </section>
            <!-- 新项目树区域/view查看项目树 -->
            <section v-show="!showSwitch.treeEditState" class="aside-tree">
              <!--render自定义渲染 -->
              <Tree
                :data="treeData.newTree"
                select-node
                :render="renderContent0"
                @on-toggle-expand="sendSwitchNode"
              ></Tree>
            </section>
          </template>
        </Col>
        <!-- 审批侧边栏弹窗 -->
        <ApprovalSidebar
          :id="approval.approvalDataId"
          :type="approval.approvalType"
          model="default"
         :flowType="4"
          ref="approvalSidebar"
          v-show="showSwitch.approvalSidebar"
          :disablePermission="true"
        />
      </Row>
    </section>
    <Modal
      ref="modal"
      @getContractTree="getContractTree"
      :htd="htd"
      :nodeId="nodeId"
      :parentId="parentId"
      :tree="treeData"
      :currentLevel="currentLevel"
    />
    <replace-modal
      ref="replaceModal"
      @getContractTree="getContractTree"
      @on-refresh="handleRefresh"
      :htd="htd"
      :nodeId="nodeId"
      :parentId="parentId"
      :tree="treeData"
    />
    <batchAddModal
      ref="batchAddModal"
      :nodeId="nodeId"
      :levelTypeId="levelTypeId"
      @on-success="handleRefresh"
    />
     <noticeModal
      ref="noticeModal"
    />
     <adminInputModal
      ref="adminInputModal"
      :htdId="htd.htdId"
    />
  </div>
</template>
<script>
import apiObj from '@/api/project-partition.js';
import ApprovalSidebar from '@/components/approval-sidebar/index.js';
import { ApprovalType } from '@/config/cfg.js';
import Htdlist from './htd-list';
import Modal from './modal';
import ReplaceModal from './replaceModal';
import batchAddModal from './batchAddModal';
import adminInputModal from './adminInputModal';
import noticeModal from './noticeModal';
// import config from '@/config';
// const baseUrl =
//   process.env.NODE_ENV === 'development'
//     ? config.baseUrl.dev
//     : config.baseUrl.pro;

export default {
  name: 'new-tree',
  components: {
    Htdlist,
    Modal,
    ApprovalSidebar,
    ReplaceModal,
    batchAddModal,
    noticeModal,
    adminInputModal
  },
  data () {
    return {
      projectName: '',
      htd: {
        htdId: 0,
        htdName: ''
      },
      levelTypeId: 0,
      // 合同段ID
      nodeId: 0,
      parentId: 0,
      // 树
      treeData: {
        // 表示新树
        tree: 'new',
        newTree: [],
        oldTree: []
      },
      currentLevel: 3, // 当前的nodeType层级
      // 按钮是否可点
      btnDisabled: {
        // 新增同级
        addBrother: true,
        // 新增下级
        addSon: true,
        // 提交审批按钮
        primary: true,
        // 复制层级
        copy: true,
        // 批量添加部位
        batch: true,
        // 管理员导入
        checkedHTD: true
      },
      // 是否隐藏
      showSwitch: {
        // 显示编辑树或者查看树
        treeEditState: false,
        // 是否显示新增按钮组
        btnGroup: false,
        // 是否显示项目树划分按钮
        projectPart: false,
        // 审批流程侧边栏是否显示
        approvalSidebar: false
      },
      // 审批相关
      approval: {
        approvalDataId: '', // 审批数据id
        approvalType: ApprovalType.SP_TYPE_XMHF // 审批数据类型
      },
      switchNodeId: -1, // 展开闭合的节点nodeId
      switchNodeExpand: null, // 展开闭合的节点expand
      dataMap: {} // tree数据map
    };
  },
  methods: {
    // 获取合同段列表
    async getContractList () {
      try {
        const resp = await apiObj.getContractList();
        // const datas = resp.data.data.htds;
        this.projectName = resp.data.data.projectName;
        console.log(this.projectName, 'this.project.projectName');
        // this.htd.htdList = datas;
        console.log('reps合同段列表', resp);
      } catch (error) {

      }
    },
    // 批量导入
    multipleInput () {
      this.$refs.noticeModal.show();
    },
    // 管理员导入
    adminInput () {
      this.$refs.adminInputModal.show();
    },
    sendSwitchNode (e) {
      this.switchNodeId = e.nodeId;
      this.switchNodeExpand = e.expand;
      let map = this.changeTreeToMap(this.treeData.newTree);
      this.$nextTick(() => {
        this.$refs['modal'].switchExpand(map);
      });
    },
    // 把treeData转成map
    changeTreeToMap (list) {
      let map = this.dataMap;
      const handleTerrData = list => {
        list.forEach(row => {
          map[row.nodeId] = map[row.nodeId] || false;
          if (row.children) {
            handleTerrData(row.children);
          }
        });
      };
      handleTerrData(list);
      const switchId = this.switchNodeId;
      const switchExpand = this.switchNodeExpand;
      for (let key in map) {
        if (switchId !== -1) {
          if (key == switchId) {
            map[key] = switchExpand;
          }
        }
      }
      return map;
    },
    // 项目树(edit可编辑)
    renderContent (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block'
            // width: '100%'
          },
          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h(
            'span',
            {
              style: {
                // display: 'inline-block',
                cursor: 'pointer',
                padding: '5px'
              },
              class: 'tree-text',
              on: {

              }
            },

            [
              h('Icon', {
                // class: 'iconfont icon-hetong2',
                class: `iconfont ${this.getLevelIcon(node.node.nodeType)}`,
                style: {
                  marginRight: '8px'
                }
              }),
              h(
                'span',
                {
                  on: {
                    click: () => {
                      this.setNodeType(data);
                      this.selfExpand(root, node, data);
                      this.nodeidAssignment(data);
                      this.btnDisabled.addBrother = false;
                      this.btnDisabled.copy = false;
                    }
                  }
                },
                data.nodeName
              )
            ]
          ),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                marginLeft: '32px'
              },
              class: 'tree-item-btn'
            },
            [
              h('Button', {
                // 新增下级
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-add-circle-outline',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.setNodeType(data);
                    this.addTreeNodeEvent(2);
                  }
                }
              }),
              h('Button', {
                // 编辑自己
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.editTreeNodeEvent();
                  }
                }
              }),
              h('Button', {
                // 查看
                props: Object.assign({}, this.buttonProps, {
                  icon: 'md-eye',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.viewTreeNodeEvent();
                  }
                }
              }),
              h('Button', {
                // 删除
                props: Object.assign({}, this.buttonProps, {
                  icon: 'md-trash',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.deleteTreeNodeEvent(data);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    // 查看的项目树，不可编辑
    renderContent0 (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block'
            // width: '100%'
          },
          class:
            data.nodeClick === true ? 'tree-item  level-click' : 'tree-item '
        },
        [
          h('span', {
            style: {
              // display: 'inline-block',
              cursor: 'pointer',
              padding: '5px'
            },
            class: 'tree-text',
            on: {

            }
          }, [
            h('Icon', {
              // props: {
              //   type: 'ios-paper-outline'
              // },
              class: `iconfont ${this.getLevelIcon(node.node.nodeType)}`,
              style: {
                marginRight: '8px'
              }
            }),
            h(
              'span',
              {
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.selfExpand(root, node, data);
                  }
                }
              },
              data.nodeName
            )
          ]),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                marginLeft: '32px'
              },
              class: 'tree-item-btn'
            },
            [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'md-eye',
                  size: 'small',
                  type: 'text'
                }),
                style: {
                  width: '27px',
                  height: '22px',
                  marginBottom: '2px'
                },
                on: {
                  click: () => {
                    this.nodeidAssignment(data);
                    this.viewTreeNodeEvent();
                  }
                }
              })
            ]
          )
        ]
      );
    },
    // 自己实现节点的展开和关闭
    selfExpand (root, node, data) {
      // 点击节点文字展开收起
      this.$set(node.node, 'expand', !node.node.expand);
      for (let i = 0; i < root.length; i++) {
        root[i].node.nodeClick = false;
      }
      data.nodeClick = true;
      this.sendSwitchNode(node.node);
    },
    replaceTreeNode () {
      this.$refs.replaceModal.show();
    },
    // 批量添加部位
    batchAddNode () {
      this.$refs.batchAddModal.show();
      this.$refs.batchAddModal.getInitTypeList();
    },
    // 根据当前项目树层级返回icon图标
    getLevelIcon (type) {
      const icons = [
        // 'icon-xingzhuangjiehe',
        'icon-hetong2',
        'icon-a-xingzhuangjiehe2',
        'icon-xingzhuangjiehebeifen',
        'icon-a-Fill12',
        'icon-a-Fill1beifen',
        'icon-a-Fill5',
        'icon-buwei',
        'icon-gongxu'
      ];
      return icons[type - 3];
    },
    // 批量复制/替换完，刷新树
    async handleRefresh () {
      const send = {
        nodeId: this.htd.htdId
      };
      try {
        const resp = await apiObj.getContractTree(send);
        const datas = resp.data.data;
        this.treeData.newTree = datas;
        console.log(this.treeData.newTree, 'this.treeData.newTree');
      } catch (error) {}
    },
    // 点击合同段某一层级
    async getContractTree (
      htdId,
      parentId,
      nodeId,
      isChecked,
      state,
      projectPart,
      flag,
      htdName
    ) {
      console.log('flag', flag);
      this.currentLevel = 3;
      this.btnDisabled.checkedHTD = false;
      // isChecked表示新增按钮组可点
      // state表示提交按钮是否可点
      // projectPart表示项目树变更按钮显示
      this.btnDisabled.addSon = isChecked; // 是否可以点击增加下一级
      this.btnDisabled.primary = state; // 是否禁点提交审批
      this.showSwitch.projectPart = projectPart;
      this.showSwitch.approvalSidebar = !isChecked;
      this.btnDisabled.addBrother = flag;
      this.btnDisabled.copy = flag;
      console.log('提交审批状态projectPart？', projectPart);
      this.confirmBtnTreeStates(state, projectPart);
      this.parentId = parentId;
      this.htd.htdId = htdId;
      this.htd.htdName = htdName;
      this.nodeId = nodeId;
      this.approval.approvalDataId = htdId;
      let send = {
        nodeId: htdId
      };
      try {
        const resp = await apiObj.getContractTree(send);
        const datas = resp.data.data;
        // this.treeData.newTree = this.deepTreeNodeClick(datas);
        this.treeData.newTree = datas;
        // this.treeData.newTree = this.deepTreeNodeClick(this.treeData.newTree);
        console.log(this.treeData.newTree, 'this.treeData.newTree');
      } catch (error) {}
    },
    deepTreeNodeClick (list, node) {
      const result = list.forEach(element => {
        item['nodeActive'] = false;
      });
      if (item.children) {
        this.deepTreeNodeClick(item.children);
      }
      if (node) {
        node.nodeActive = true;
      }
      console.log(result, 'result');
      return result;
    },
    // 判断新增按钮组是否显示，判断当前树是编辑还是只可查看
    confirmBtnTreeStates (state, projectPart) {
      if (!state && !projectPart) {
        // state为假。 表示提交审批按钮可点，树可编辑
        // projectPart为假，表示提交审批显示，项目变更按钮隐藏
        this.showSwitch.btnGroup = true;
        this.showSwitch.treeEditState = true;
      } else {
        // 表示提交按钮禁用，即树不可编辑
        this.showSwitch.btnGroup = false;
        this.showSwitch.treeEditState = false;
      }
    },

    // 新增同级/新增下级/树新增按钮事件
    addTreeNodeEvent (type) {
      this.$nextTick(() => {
        this.$refs['modal'].showTreeNodeModal(type);
      });
    },
    // 编辑节点按钮事件
    editTreeNodeEvent () {
      this.$nextTick(() => {
        this.$refs['modal'].editTreeNodeModal();
      });
    },
    // 删除节点按钮事件
    deleteTreeNodeEvent (node) {
      this.$nextTick(() => {
        this.$refs['modal'].deleteTreeNodeModal(node);
      });
    },
    // 查看节点按钮事件
    viewTreeNodeEvent () {
      this.$nextTick(() => {
        this.$refs['modal'].viewTreeNodeModal();
      });
    },
    // 给nodeId和parentId赋值
    nodeidAssignment (data) {
      const { nodeId, levelTypeId, parentId } = data;
      this.nodeId = nodeId;
      this.levelTypeId = levelTypeId;
      this.parentId = parentId;
    },
    // 获取并设置当前nodetype节点
    setNodeType (data) {
      this.currentLevel = data.nodeType + 1;
      this.btnDisabled.batch = this.currentLevel === 4;
    },
    // 导出Excel
    async exportExcel () {
      // let url = `${baseUrl}/pt/export?id=${this.htd.htdId}`;
      // window.open(url);
      apiObj.exportExcel2023(this.htd.htdId).then(res => {
        console.log(res);
        if (res.data.code && res.data.code !== 200) {
          this.$Message.error(res.data.msg);
          return;
        }
        let blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel;charset=utf-8' // 文件类型
        });
        let eLink = document.createElement('a');
        eLink.download = this.htd.htdName + '.xls';
        eLink.style.display = 'none';
        eLink.href = URL.createObjectURL(blob);
        document.body.appendChild(eLink);
        eLink.click();

        document.body.removeChild(eLink);
        URL.revokeObjectURL(eLink.href);
      });
    },
    // 提交审批：把项目树和审批流程提交
    async submitPrimaryApproval () {
      const approvalList = this.$refs.approvalSidebar.getApprovalData();
      console.log(888, approvalList);
      if (approvalList && approvalList.length === 0) {
        this.$Modal.warning({
          title: '提示',
          content: '请至少添加一个审批节点'
        });
      } else {
        const send = {
          busVo: {
            dataid: this.htd.htdId
          },
          list: approvalList
        };
        try {
          const resp = await apiObj.submitApprovalBtn(send);
          console.log('提交审批后的resp', resp);
          this.confirmBtnTreeStates(true);
          this.btnDisabled.primary = true;
          this.$refs.htdList.getContractList();
          // 刷新流程树
          this.$refs.approvalSidebar.getApprovalInfo();
        } catch (error) {}
      }
    },
    // 复制项目树某节点层级
    async copyTreeNode () {
      console.log('复制');
      const send = { nodeId: this.nodeId };
      const resp = await apiObj.copyTreeNode(send);
      this.$nextTick(() => {
        this.$refs['modal'].refreshContractTree();
      });
      console.log('复制的节点', resp);
    },
    // 由变更记录切换到变更列表页
    changeToRecordList () {
      this.$router.push({
        path: 'project-partition/record-list'
        // query: { 'nodeId': nodeId, 'reportId': reportId }
      });
    },
    // 直接跳转到项目变更历史页面
    toOldTreelog () {
      this.$router.push({
        path: 'project-partition/old-tree',
        query: { state: 1 }
      });
    }
  },

  mounted () {
    this.treeData.tree = 'new';
    this.getContractList();
  }
};
</script>
<style lang="less" scoped>
@fontSize: 20px;
@shortWH: 5px;
@middleWH: 20px;
@longWH: 100px;
body {
  height: 100%;
  padding: 0 !important;
  .project-tree-page {
    width: 100%;
    height: 100%;
    .btn-color {
      border-color: #5cadff;
      color: #5cadff;
    }
    .p-title {
      font-size: 0.8 * @fontSize;
    }
    .btn-color {
      margin-right: 2 * @shortWH;
    }

    .section {
      margin-top: 2 * @shortWH;
      .aside-tree {
        .tree-item:hover {
          cursor: pointer;
        }
      }
    }
  }
  // .my-span {
  //   display: block;
  // }
  .tree-text:hover {
    cursor: pointer;
  }
}
/deep/ .level-click {
  .tree-text {
    background: #5a6fce !important;
    border-radius: 3px;
    color: #fff !important;
    display:inline-block;
  }
}
/deep/ .tree-item {
  .ivu-btn {
    visibility: hidden;
  }
}
/deep/ .tree-item:hover {
  .tree-text {
    color: rgb(90, 111, 206);
  }
  .ivu-btn {
    visibility: visible;
  }
}
@import '../../../assets/css/hoverscollor.css';

</style>
